package com.lhy.framework.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.lhy.framework.beans.BeansException;
import com.lhy.framework.beans.factory.DisposableBean;

import java.lang.reflect.Method;

/**
 * @ClassName DisposableBeanAdapter
 * @Description 定义销毁方法适配器（接口和配置）
 * @Author lihaiyang
 * @Date 2022/9/12 16:22
 * @Version 1.0
 */
public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;

    private final String beanName;

    private final String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, String destroyMethodName) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = destroyMethodName;
    }

    @Override
    public void destroy() throws Exception {
        // 1、实现接口 DisposableBean
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        // 2、配置信息 destroy-method 判断是为了避免二次执行销毁
        if (StrUtil.isNotBlank(destroyMethodName) && !(bean instanceof DisposableBean && StrUtil.equals("destroy", this.destroyMethodName))) {
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            if (null == destroyMethod) {
                throw new BeansException("Cloud not find a destroy method named '" + destroyMethodName + "' on bean with name '" + beanName + "'");
            }
            destroyMethod.invoke(bean);
        }

    }
}
